package com.jjyu.controller;

import com.jjyu.entity.Result;
import com.jjyu.entity.User;
import com.jjyu.service.UserService;
import com.jjyu.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public Result list() {
        List<User> userList = userService.list();
        // 打印所有的用户
        userList.stream().toList().forEach(System.out::println);
        return Result.success(userList);
    }

    @DeleteMapping("/delete")
    public Result delete(String name) {
        // 删除用户
        Map<String, Object> nameMap = Map.of("name", name);
        boolean remove = userService.removeByMap(nameMap);
        if (remove) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }

    @PostMapping("/register")
    public Result register(String name, String email, String password) {
        //查询用户
        User user = userService.findByUserName(name);
        if (user == null) {
            // 注册代码
            User register = userService.register(name, email, password);

            if (register != null) {
                return Result.success(register);
            }

        } else {
            return Result.error("用户名已存在");
        }
        return Result.error("注册失败");
    }

    @PostMapping("/update")
    public Result update(String name, String email, String password) {
        User user = new User();
        user.setName(name);
        user.setEmail(email);
        user.setPassword(Md5Utils.stringToMD5(password));
        boolean update = userService.update(user, null);
        if (update) {
            return Result.success(user);
        }
        return Result.error("更新失败");
    }
}
